using System;
using System.IO;
using PublicDomain.Copy;
using SevenZSharp.Engines;

namespace SevenZSharp.Decoders
{
   /// <summary>
   /// 
   /// </summary>
   public class ShellDecoder : CompressionDecoder
   {
      private readonly ShellEngine m_engine;

      /// <summary>
      /// Initializes a new instance of the <see cref="ShellDecoder"/> class.
      /// </summary>
      /// <param name="engine">The engine.</param>
      public ShellDecoder(ShellEngine engine)
      {
         m_engine = engine;
      }

      /// <summary>
      /// Decodes a single file. <paramref name="inStream"/> is the
      /// encoded file which will be decoded into <paramref name="outStream"/>.
      /// If <paramref name="outStream"/> does not exist, it will be created.
      /// </summary>
      /// <param name="inStream">The in stream.</param>
      /// <param name="outStream">The out stream.</param>
      public override void DecodeSingleFile(FileStream inStream, FileStream outStream)
      {
         throw new Exception("The method or operation is not implemented.");
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="inFile"></param>
      /// <param name="outFile"></param>
      public override void DecodeSingleFile(string inFile, string outFile)
      {
         DecodeIntoDirectory(inFile, outFile);
      }

      /// <summary>
      /// Recursively decodes the compressed file in <paramref name="inFile"/>
      /// into the output directory specified by <paramref name="outDirectory"/>.
      /// If <paramref name="outDirectory"/> does not exist, it will be created.
      /// </summary>
      /// <param name="inFile">The in file.</param>
      /// <param name="outDirectory">The out directory.</param>
      public override void DecodeIntoDirectory(string inFile, string outDirectory)
      {
         if (inFile == null) throw new ArgumentNullException("inFile");
         if (outDirectory == null) throw new ArgumentNullException("outDirectory");

         if (File.Exists(outDirectory))
         {
            outDirectory = Path.GetDirectoryName(outDirectory);

            if (outDirectory.Length == 0)
            {
               outDirectory = Environment.CurrentDirectory;
            }
         }

         CompressionFormat format = CompressionEngine.InferCompressionFormat(inFile);
         switch (format)
         {
            default:
               ProcessHelper process = m_engine.GetDecodeShellProcess(inFile, outDirectory);
               process.StartAndWaitForExit(true);
               break;
         }
      }
   }
}